import { Button } from "antd";
import { useEffect, useRef, useState } from "react";
import { io, Socket } from "socket.io-client";
import "./index.scss";
import {
	chatHistoryServer,
	chatroomListServer,
} from "@/servers/chatroomServer";
import TextArea from "antd/es/input/TextArea";
import getUserInfo from "@/hooks/getUserInfo";
import { useLocation } from "react-router-dom";

interface JoinRoomPayload {
	chatroomId: number;
	userId: number;
}

interface SendMessagePayload {
	sendUserId: number;
	chatroomId: number;
	message: Message;
}

interface Message {
	type: "text" | "image";
	content: string;
}

type Reply =
	| {
			type: "sendMessage";
			userId: number;
			message: ChatHistoryType;
	  }
	| {
			type: "joinRoom";
			userId: number;
	  };

interface chatroomItemType {
	id: number;
	name: string;
	type: boolean;
	createTime: Date;
	updateTime: Date;
}

interface UserInfo {
	id: number;
	username: string;
	nickName: string;
	email: string;
	createTime: Date;
	headPic: string;
}

interface ChatHistoryType {
	id: number;
	content: string;
	type: number;
	chatroomId: number;
	senderId: number;
	createTime: Date;
	sender: UserInfo;
}

export default function Chat() {
	const [activeId, setActive] = useState<number>();
	const isActive = (id: number) => id === activeId;
	const [chatroomList, setChatroomList] = useState<chatroomItemType[]>([]);
	const [chatHistory, setChatHistory] = useState<ChatHistoryType[]>([]);
	const [inputText, setInputText] = useState("");

	const getChatroomList = async (name?: string) => {
		const res = await chatroomListServer(name || "");
		const { code, data } = res.data;
		if (code === 200 || code === 201) {
			setChatroomList(data);
		}
	};

	const getChatHistory = async (chatroomId: number) => {
		const res = await chatHistoryServer(chatroomId);
		const { code, data } = res.data;
		if (code === 200 || code === 201) {
			setChatHistory(data);
		}
	};


    const scrollFun = () => {
        setTimeout(() => {
            document.getElementById('bottom-bar')?.scrollIntoView({block: 'end'});
        }, 300);
    }

	const socketRef = useRef<Socket>();

    const location = useLocation();

    useEffect(() => {
        if(location.state?.chatroomId){
            setActive(location.state?.chatroomId);
            getChatHistory(location.state?.chatroomId)
            scrollFun()
        }
    }, [location.state?.chatroomId]);

	useEffect(() => {
		if(!activeId){
            return
        }
		const socket = (socketRef.current = io("http://localhost:3077"));
		socket.on("connect", function () {
			const payload: JoinRoomPayload = {
				chatroomId: activeId,
				userId: getUserInfo().id,
			};
			socket.emit("joinRoom", payload);
			socket.on("message", (reply: Reply) => {
                if(reply.type === 'sendMessage') {
                    setChatHistory((chatHistory) => chatHistory ? [...chatHistory, reply.message] : [reply.message]);   
                    scrollFun()
                }
			});
		});
        return ()=>{
            socket.disconnect()
        }
	}, [activeId]);

    useEffect(()=>{
        getChatroomList();
    } , [])

    // 封装发送消息方法
	const sendMessage = (value: string) => {
        if(!value){
            return
        }
        if(!activeId){
            return
        }
		const payload: SendMessagePayload = {
			sendUserId: getUserInfo().id,
			chatroomId: activeId,
			message: {
				type: "text",
				content: value,
			},
		};
		socketRef.current?.emit("sendMessage", payload);
	}

	return (
		<div id="chat-container">
			<div className="chat-room-list">
				{chatroomList.map((item) => (
					<div
						className={`chat-room-item ${
							isActive(item.id) && "active"
						}`}
						data-id={item.id}
						key={item.id}
						onClick={() => {
							getChatHistory(item.id);
							setActive(item.id);
                            scrollFun()
						}}
					>
						{item.name}
					</div>
				))}
			</div>
			<div className="message-list">
				{chatHistory.map((item) => (
					<div
                        className={`message-item ${item.senderId === getUserInfo().id ? 'from-me' : ''}`}
						data-id={item.id}
						key={item.id}
					>
						<div className="message-sender">
							<img src={item.sender.headPic} />
							<span className="sender-nickname">
								{item.sender.nickName}
							</span>
						</div>
						<div className="message-content">{item.content}</div>
					</div>
				))}
                <div id="bottom-bar" key='bottom-bar'></div>
			</div>
			<div className="message-input">
				<div className="message-type">
					<div className="message-type-item">表情</div>
					<div className="message-type-item">图片</div>
					<div className="message-type-item">文件</div>
				</div>
				<div className="message-input-area">
					<TextArea
						className="message-input-box"
						value={inputText}
						onChange={(e) => {
							setInputText(e.target.value);
						}}
					/>
					<Button
						className="message-send-btn"
						type="primary"
						onClick={() => {
							sendMessage(inputText);
							setInputText("");
						}}
					>
						发送
					</Button>
				</div>
			</div>
		</div>
	);
}
